package thread.hook;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;

/**
 * hook线程
 *
 * @author lwmzzz
 * @version 1.0
 * @date 2021/5/16 22:41
 */
public class Test {
    public static void main(String[] args) {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("JVM退出，会启动当前Hook线程，在Hook线程中删除.lock文件");
            getLockFile().toFile().delete();
        }));

        if (getLockFile().toFile().exists()) {
            throw new RuntimeException("程序已启动!");
        } else {
            try {
                getLockFile().toFile().createNewFile();
                System.out.println("程序在启动时创建了lock文件");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        for (int i = 0; i < 100; i++) {
            System.out.println("程序正在运行");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static Path getLockFile() {
        return Paths.get("", "tmp.lock");
    }
}
